#!/bin/bash
# ver 1.1
pkg=${1};
ver=${2};

usage()
{
	echo "mkpkg: Usage: mkpkg name version";
	exit 0;
}

rn()
{
	cp ${1} ${1}.old
	cat ${1}.old | sed "s/^prefix.*=\s\/usr\/local/prefix = \/tmp\/pkgs\/${pkg}\/usr\/local/g" > ${1} ;
}

if [ -z "$pkg" ] || [ -z "$ver" ]; then
	usage;
fi;

echo "Creating /tmp/pkgs/${pkg} directory...";
mkdir -p /tmp/pkgs/${pkg}/usr/local;

echo "Patching Makefiles...";
bool=0;
find ./ | grep Makefile$ | while read i; #| xargs grep -il "^prefix" | while read i;
do 
	if [ -n `grep -il "^prefix" ${i}` ];then
		rn ${i};
		$bool=1;
	else
	       	if [ -n `grep -il "^dest.*=" ${i}` ]; then
			rn ${i};
			$bool=1;
		fi
	fi
done;

if [ -z ${bool} ]; then
	echo "Error: Cannot find prefix in makefiles.";
	exit 1;
fi

echo "Copyring files...";
make install > /dev/null && cd /tmp/pkgs/${pkg};

echo "Making pakage...";
makepkg -l y -c y ../${pkg}-${ver}.txz;

echo "Package /tmp/pkgs/${pkg}-${ver}.txz created."

if [ -z "$USER_BUILDS" ]; then
        USER_BUILDS=${HOME}/Builds;
	if [ ! -d "${USER_BUILDS}" ]; then
		mkdir -p ${USER_BUILDS};
	fi;
fi;

mv /tmp/pkgs/${pkg}-${ver}.txz ${USER_BUILDS};
echo "Pakage ${pkg}-${ver}.txz moved into ${USER_BUILDS}.";

